KindEditor.plugin('filesystem', function(K) {
	var self = this, name = 'filesystem',
	formatUploadUrl = K.undef(self.formatUploadUrl, true),
	uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),	
	imageSizeLimit = K.undef(self.imageSizeLimit, '1MB'),
	imageFileTypes = K.undef(self.imageFileTypes, '*.jpg;*.gif;*.png'),
	imageUploadLimit = K.undef(self.imageUploadLimit, 20),
	filePostName = K.undef(self.filePostName, 'imgFile'),
	lang = self.lang(name + '.');
	fileManagerJson = K.undef(self.fileManagerJson, self.basePath + 'php/file_manager_json.php'),
	createDirJson = K.undef(self.createDirJson, self.basePath + 'php/create_dir_json.php'),
	imgPath = self.pluginsPath + name + '/images/',
	lang = self.lang(name + '.');
	
	function makeFileTitle(filename, filesize, datetime) {
		return filename + ' (' + Math.ceil(filesize / 1024) + 'KB, ' + datetime + ')';
	};
	function bindTitle(el, data) {
		if (data.is_dir) {
			el.attr('title', data.filename);
		} else {
			el.attr('title', makeFileTitle(data.filename, data.filesize, data.datetime));
		}
	};
	
	self.plugin.multiImageDialog = function(options) {
		var clickFn = options.clickFn,
			uploadDesc = K.tmpl(lang.uploadDesc, {uploadLimit : imageUploadLimit, sizeLimit : imageSizeLimit});
		var html = [
			'<div style="padding:20px;">',
			'<div class="swfupload">',
			'</div>',
			'</div>'
		].join('');
		var dialog = self.createDialog({
			name : name,
			width : 650,
			height : 510,
			title : self.lang(name),
			body : html,
			previewBtn : {
				name : lang.insertAll,
				click : function(e) {
					clickFn.call(self, swfupload.getUrlList());
				}
			},
			yesBtn : {
				name : lang.clearAll,
				click : function(e) {
					swfupload.removeFiles();
				}
			},
			beforeRemove : function() {
				swfupload.remove();
			}
		}),
		div = dialog.div;

		var swfupload = K.swfupload({
			container : K('.swfupload', div),
			buttonImageUrl : imgPath + (self.langType == 'zh_CN' ? 'select-files-zh_CN.png' : 'select-files-en.png'),
			buttonWidth : self.langType == 'zh_CN' ? 72 : 88,
			buttonHeight : 23,
			fileIconUrl : imgPath + 'image.png',
			uploadDesc : uploadDesc,
			startButtonValue : lang.startUpload,
			uploadUrl : K.addParam(uploadJson, 'dir=image'),
			flashUrl : imgPath + 'swfupload.swf',
			filePostName : filePostName,
			fileTypes : '*.jpg;*.jpeg;*.gif;*.png;*.bmp',
			fileTypesDesc : 'Image Files',
			fileUploadLimit : imageUploadLimit,
			fileSizeLimit : imageSizeLimit,
			postParams :  K.undef(self.extraFileUploadParams, {}),
			queueLimitExceeded : lang.queueLimitExceeded,
			fileExceedsSizeLimit : lang.fileExceedsSizeLimit,
			zeroByteFile : lang.zeroByteFile,
			invalidFiletype : lang.invalidFiletype,
			unknownError : lang.unknownError,
			pendingMessage : lang.pending,
			errorMessage : lang.uploadError,
			afterError : function(html) {
				self.errorDialog(html);
			}
		});

		return dialog;
	};

	self.plugin.filesystemDialog = function(options) {
		var width = K.undef(options.width, 650),
			height = K.undef(options.height, 510),
			dirName = K.undef(options.dirName, ''),
			viewType = K.undef(options.viewType, 'VIEW').toUpperCase(), // "LIST"
																		// or
																		// "VIEW"
			clickFn = options.clickFn;
		var html = [
			'<div style="padding:10px 20px;">',
			// header start
			'<div class="ke-plugin-filemanager-header">',
			// left start
			'<div class="ke-left">',
			'<img class="ke-inline-block" name="moveupImg" src="' + imgPath + 'go-up.gif" width="16" height="16" border="0" alt="" /> ',
			'<a class="ke-inline-block" name="moveupLink" href="javascript:;">' + lang.moveup + '</a>',
			'<img class="ke-inline-block" name="createDirImg" src="' + imgPath + 'create-dir.gif" width="16" height="16" border="0" alt="" /> ',
			'<a class="ke-inline-block" name="createDirLink" href="javascript:;">' + lang.createDir+ '</a>',
			'<img class="ke-inline-block" name="refreshImg" src="' + imgPath + 'create-dir.gif" width="16" height="16" border="0" alt="" /> ',
			'<a class="ke-inline-block" name="refreshLink" href="javascript:;">' + lang.refresh+ '</a>',
			'<img class="ke-inline-block" name="uploadImg" src="' + imgPath + 'create-dir.gif" width="16" height="16" border="0" alt="" /> ',
			'<a class="ke-inline-block" name="uploadLink" href="javascript:;">' + lang.upload+ '</a>',			
			'</div>',
			// right start
			'<div class="ke-right">',
			'<input name="currentDir" type="hidden" value=""/>',
			lang.viewType + ' <select class="ke-inline-block" name="viewType">',
			'<option value="VIEW">' + lang.viewImage + '</option>',
			'<option value="LIST">' + lang.listImage + '</option>',
			'</select> ',
			lang.orderType + ' <select class="ke-inline-block" name="orderType">',
			'<option value="NAME">' + lang.fileName + '</option>',
			'<option value="SIZE">' + lang.fileSize + '</option>',
			'<option value="TYPE">' + lang.fileType + '</option>',
			'</select>',
			'</div>',
			'<div class="ke-clearfix"></div>',
			'</div>',
			// body start
			'<div class="ke-plugin-filemanager-body"></div>',
			'</div>'
		].join('');
		var dialog = self.createDialog({
			name : name,
			width : width,
			height : height,
			title : self.lang(name),
			body : html
		}),
		div = dialog.div,
		bodyDiv = K('.ke-plugin-filemanager-body', div),
		moveupImg = K('[name="moveupImg"]', div),
		moveupLink = K('[name="moveupLink"]', div),
		createDirLink = K('[name="createDirLink"]', div),
		uploadLink = K('[name="uploadLink"]', div),
		refreshLink = K('[name="refreshLink"]', div),
		viewServerBtn = K('[name="viewServer"]', div),
		viewTypeBox = K('[name="viewType"]', div),
		orderTypeBox = K('[name="orderType"]', div);
		currentBox = K('[name="currentDir"]', div);
		function reloadPage(path, order, func) {
			var param = 'order=' + order + '&dir=' + dirName;
			dialog.showLoading(self.lang('ajaxLoading'));
			K.ajax(K.addParam(fileManagerJson, param + '&' + new Date().getTime()), function(data) {
				dialog.hideLoading();
				func(data);
			},"POST",{path: path});
		}
		var elList = [];
		function bindEvent(el, result, data, createFunc) {
			var fileUrl = data.fileUrl,
				dirPath = result.current_dir_path + data.filename + '/';
			if (data.is_dir) {
				el.click(function(e) {
					reloadPage(dirPath, orderTypeBox.val(), createFunc);
				});
			} else if (data.is_photo) {
				el.click(function(e) {
					clickFn.call(this, fileUrl, data.filename);
				});
			} else {
				el.click(function(e) {
					clickFn.call(this, fileUrl, data.filename);
				});
			}
			elList.push(el);
		};		
		
		function createDirDialog(options){
			var html = ['<div style="padding:20px;">',
						'<div class="ke-dialog-row">',
						'<label for="keName">' + lang.dirName + '</label>',
						'<input class="ke-input-text" type="text" id="keName" name="name" value="" style="width:150px;" />',
						'</div>',
						'</div>'].join('');
			var dialog = self.createDialog({
				name : lang.createDir,
				width : 300,
				title : lang.createDir,
				body : html,
				yesBtn : {
					name : self.lang('yes'),
					click : function(e) {						
						var newDirName = nameBox.val();
						dialog.showLoading(self.lang('ajaxLoading'));						
						var order = orderTypeBox.val();				
						var viewType = viewTypeBox.val();
						var currentPath = currentBox.val();
						
						K.ajax(K.addParam(createDirJson,'&' + new Date().getTime()), function(data) {
							dialog.hideLoading();
							self.hideDialog();		
							viewType == 'VIEW' ? createView(data) : createList(data);						
						},"POST",{order: order,path: currentPath, newdir: newDirName});
					}
				}
			});
			
			var div = dialog.div,
			nameBox = K('input[name="name"]', div);
			return dialog;
		};
		
		function createCommon(result, createFunc) {
			// remove events
			K.each(elList, function() {
				this.unbind();
			});
			moveupLink.unbind();
			createDirLink.unbind();
			refreshLink.unbind();
			viewTypeBox.unbind();
			orderTypeBox.unbind();
			uploadLink.unbind();
			currentBox.val(result.current_dir_path);
			// add events
			if (result.current_dir_path) {
				moveupLink.click(function(e) {
					reloadPage(result.moveup_dir_path, orderTypeBox.val(), createFunc);
				});
			}
			refreshLink.click(function(e){
				reloadPage(result.current_dir_path, orderTypeBox.val(), createFunc);
			});
			createDirLink.click(function(e) {
				createDirDialog();
			});
			uploadLink.click(function(e){
				self.plugin.multiImageDialog({});
			});
			function changeFunc() {
				if (viewTypeBox.val() == 'VIEW') {
					reloadPage(result.current_dir_path, orderTypeBox.val(), createView);
				} else {
					reloadPage(result.current_dir_path, orderTypeBox.val(), createList);
				}
			}
			viewTypeBox.change(changeFunc);
			orderTypeBox.change(changeFunc);
			bodyDiv.html('');
		}
		function createList(result) {
			createCommon(result, createList);
			var table = document.createElement('table');
			table.className = 'ke-table';
			table.cellPadding = 0;
			table.cellSpacing = 0;
			table.border = 0;
			bodyDiv.append(table);
			var fileList = result.file_list;
			for (var i = 0, len = fileList.length; i < len; i++) {
				var data = fileList[i], row = K(table.insertRow(i));
				row.mouseover(function(e) {
					K(this).addClass('ke-on');
				})
				.mouseout(function(e) {
					K(this).removeClass('ke-on');
				});
				var iconUrl = imgPath + (data.is_dir ? 'folder-16.gif' : 'file-16.gif'),
					img = K('<img src="' + iconUrl + '" width="16" height="16" alt="' + data.filename + '" align="absmiddle" />'),
					cell0 = K(row[0].insertCell(0)).addClass('ke-cell ke-name').append(img).append(document.createTextNode(' ' + data.filename));
				if (!data.is_dir || data.has_file) {
					row.css('cursor', 'pointer');
					cell0.attr('title', data.filename);
					bindEvent(cell0, result, data, createList);
				} else {
					cell0.attr('title', lang.emptyFolder);
				}
				K(row[0].insertCell(1)).addClass('ke-cell ke-size').html(data.is_dir ? '-' : Math.ceil(data.filesize / 1024) + 'KB');
				K(row[0].insertCell(2)).addClass('ke-cell ke-datetime').html(data.datetime);
				K(row[0].insertCell(3)).addClass('ke-cell').html("删");
			}
		}
		function createView(result) {
			createCommon(result, createView);
			var fileList = result.file_list;
			for (var i = 0, len = fileList.length; i < len; i++) {
				var data = fileList[i],
					div = K('<div class="ke-inline-block ke-item"></div>');
				bodyDiv.append(div);
				var photoDiv = K('<div class="ke-inline-block ke-photo"></div>')
					.mouseover(function(e) {
						K(this).addClass('ke-on');
					})
					.mouseout(function(e) {
						K(this).removeClass('ke-on');
					});
				
				div.append(photoDiv);
				var fileUrl = data.previewUrl,
					iconUrl = data.is_dir ? imgPath + 'folder-64.gif' : (data.is_photo ? fileUrl : imgPath + 'file-64.gif');
				var img = K('<img src="' + iconUrl + '" width="80" height="80" alt="' + data.filename + '" />');
				if (!data.is_dir || data.has_file) {
					photoDiv.css('cursor', 'pointer');
					bindTitle(photoDiv, data);
					bindEvent(photoDiv, result, data, createView);
				} else {
					photoDiv.attr('title', lang.emptyFolder);
				}
				photoDiv.append(img);
				div.append('<div class="ke-name" title="' + data.filename + '">' + data.filename + '</div>');
			}
		}
		viewTypeBox.val(viewType);
		reloadPage('', orderTypeBox.val(), viewType == 'VIEW' ? createView : createList);
		return dialog;
	};
	
	self.plugin.filesystem = {
		edit : function() {
			self.plugin.filesystemDialog({clickFn : function(url, title, width, height, border, align) {
				self.exec('insertimage', url, title, width, height, border, align);
				// Bugfix: [Firefox] 上传图片后，总是出现正在加载的样式，需要延迟执行hideDialog
				setTimeout(function() {
					self.hideDialog().focus();
				}, 0);
			}});
		},
		'delete' : function() {
			var target = self.plugin.getSelectedImage();
			if (target.parent().name == 'a') {
				target = target.parent();
			}
			target.remove();
		}
	};
	self.clickToolbar(name, self.plugin.filesystem.edit);
});
